const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const log4js = require('./utils/log4j')
const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const koajwt = require('koa-jwt')
const cors = require('koa2-cors')
const path = require('path')

const util = require('./utils/util')
const users = require('./routes/users')
const menus = require('./routes/menus')
const roles = require('./routes/roles')
const depts = require('./routes/depts')
const leave = require('./routes/leave')
// 微信路由接口
const wxuser = require('./routes/wx-user')
// ocr识别接口
const ocrText = require('./routes/ocr')

const koaBody = require('koa-body')

// 解析图片
app.use(
	koaBody({
		multipart: true,
		formidable: {
			uploadDir: path.join(__dirname, '/public/uploads'), // 放置图片区域
			keepExtensions: true, // 保持图片后缀名字
			maxFileSize: 200 * 1024 * 1024 // 设置上传文件大小最大限制，默认2M
		}
	})
)

// error handler
onerror(app)

require('./config/db')

// middlewares
app.use(
	bodyparser({
		enableTypes: ['json', 'form', 'text']
	})
)
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(
	views(__dirname + '/views', {
		extension: 'pug'
	})
)

// logger
app.use(async (ctx, next) => {
	log4js.info(`get params:${JSON.stringify(ctx.request.query)}`)
	log4js.info(`post params:${JSON.stringify(ctx.request.body)}`)
	await next().catch((err) => {
		if (err.status == '401') {
			ctx.status = 200
			ctx.body = util.fail('Token认证失败', util.CODE.AUTH_ERROR)
		} else {
			throw err
		}
	})
})

app.use(cors())

// kwt
app.use(
	koajwt({ secret: 'imooc' }).unless({
		path: [
			/^\/api\/users\/login/,
			/^\/api\/users\/operate/,
			/^\/api\/wx\/login/,
			/^\/api\/wx\/test/,
			/^\/api\/wx\/uploadimg/
		]
	})
)

router.prefix('/api')

router.use(users.routes(), users.allowedMethods())
router.use(menus.routes(), menus.allowedMethods())
router.use(roles.routes(), roles.allowedMethods())
router.use(depts.routes(), depts.allowedMethods())
router.use(leave.routes(), leave.allowedMethods())
//ocrText
router.use(ocrText.routes(), ocrText.allowedMethods())
// wx-user
router.use(wxuser.routes(), wxuser.allowedMethods())
app.use(router.routes(), router.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
	log4js.error(`${err.stack}`)
})

module.exports = app
